import React, { useState, useRef } from "react";
import * as homeService from '../services/homeService';

export default function useHomeState() {

    const [currentWeather, setCurrentWeather] = useState({});
    const [userCount, setUserCount] = useState(0);
    const [visitCount, setVisitCount] = useState(0);

    const RAGChartRef = useRef(null);
    const AgentChartRef = useRef(null);
    const RAGNumberTimeChart = useRef(null);
    const AgentNumberTimeChart = useRef(null);

    const snatch_current_weather = () => {
        homeService.snatchCurrentWeather({ "cityCode": "101110101" }).then(res => {
            if (res.code == 200) {
                setCurrentWeather(res.data);
            }
        });
    }

    const refresh_statistics = () => {
        homeService.refreshStatistics({}).then(res => {
            if (res.code == 200) {
                process_statistics(res.data);
            }
        });
    }

    const process_statistics = (data) => {
        if (data.user_count) {
            setUserCount(data.user_count);
        }
        if (data.visit_count) {
            setVisitCount(data.visit_count);
        }
        if (data.history_records && data.memory_details) {
            let result = homeService.processHistoryMemory(data.history_records, data.memory_details);
            let { ragDialogNumbers, ragResponseTimes, agentDialogNumbers, agentResponseTimes } = result;
            if (RAGChartRef.current) {
                homeService.ragModulePieChat(RAGChartRef);
            }
            if (AgentChartRef.current) {
                homeService.agentModulePieChat(AgentChartRef);
            }
            if (RAGNumberTimeChart.current) {
                homeService.ragNumberTimeChat(RAGNumberTimeChart, ragDialogNumbers, ragResponseTimes);
            }
            if (AgentNumberTimeChart.current) {
                homeService.agentNumberTimeChat(AgentNumberTimeChart, agentDialogNumbers, agentResponseTimes);
            }
        }
    }

    const process_event_source = (eventSource) => {
        console.log('========== useHomeState process_event_source ==========');
        eventSource.onmessage = function (e) {
            const data = JSON.parse(e.data);
            process_statistics(data);
        }

        eventSource.addEventListener('connect',  (e) => {
            console.log('Connected to server');
        });

        eventSource.addEventListener('complete',  (e) => {
            console.log('Streaming completed');
            eventSource.close();
        });

        // 页面关闭时关闭连接
        window.addEventListener('beforeunload', () => {
            eventSource.close();
        });
    }

    return {
        userCount, visitCount, currentWeather, snatch_current_weather, refresh_statistics, process_event_source,
        RAGChartRef, AgentChartRef, RAGNumberTimeChart, AgentNumberTimeChart
    };
}
